import { Injectable } from '@nestjs/common'
import { CreateSubjectDto } from './dto/create-subject.dto'
// import { UpdateSubjectDto } from './dto/update-subject.dto'
import { InjectModel } from '@nestjs/mongoose'
import { Subject } from 'src/schema/subject.schema'
import { TestPaper } from 'src/schema/testpaper.schema'
import { Shijuan } from 'src/schema/shijuan.schema'
import { Model } from 'mongoose'
import { GenerateShijuanDto } from './dto/generate-shijuan.dto'

@Injectable()
export class SubjectsService {
  constructor(
    @InjectModel(Subject.name) private subjectModel: Model<Subject>,
    @InjectModel(TestPaper.name) private testPaperModel: Model<TestPaper>,
    @InjectModel(Shijuan.name) private shijuanModel: Model<Shijuan>
  ) {}

  create(createSubjectDto: CreateSubjectDto) {
    console.log('createSubjectDto', createSubjectDto)
    const createdSubject = new this.subjectModel(createSubjectDto)
    return createdSubject.save()
  }

  findAll(): Promise<Subject[]> {
    return this.subjectModel.find().exec()
  }

  // 随机选出40个不重复的题目
  async findRandomSubjects(name: GenerateShijuanDto) {
    const count = await this.subjectModel.countDocuments()
    const randomSubjects = []
    const randomIndexs = []
    while (randomIndexs.length < 40 && randomIndexs.length < count) {
      const randomIndex = Math.floor(Math.random() * count)
      if (randomIndexs.indexOf(randomIndex) === -1) {
        randomIndexs.push(randomIndex)
        randomSubjects.push(
          await this.subjectModel.findOne().skip(randomIndex).exec()
        )
      }
    }

    // 打乱每个题目下，选项的顺序
    randomSubjects.forEach(subject => {
      subject.options = subject.options.sort(() => Math.random() - 0.5)
    })

    return await this.generateTestPaper(randomSubjects, name)

    // return randomSubjects
  }

  // 根据出好的题目，生成一份试卷
  async generateTestPaper(randomSubjects, name: GenerateShijuanDto) {
    const subjectIds = []
    for (const subject of randomSubjects) {
      const testPaper = new this.testPaperModel({
        subject: subject._id,
        randomOptions: subject.options
      })
      const oneSubject = await testPaper.save()
      console.log('oneSubject', oneSubject)
      subjectIds.push(oneSubject._id)
    }

    console.log('subjectIds', subjectIds)
    console.log('name', name)

    const shijuan = new this.shijuanModel({
      subjectIds: subjectIds,
      name: name.name
    })
    const shijuanData = await shijuan.save()
    console.log('shijuanData', shijuanData)

    return shijuanData._id
  }

  async getShijuan(subjectId: string) {
    // 根据试卷id，找到试卷下的所有题目
    // 并且找到所有的原始题目
    // 查询第三级的数据
    const shijuan = await this.shijuanModel
      .findById(subjectId)
      // .populate({ path: 'subjectIds', model: 'TestPaper' })
      // .populate({ path: 'subjectIds.subject', model: 'Subject' })
      .exec()

    console.log('shijuan', shijuan)

    // return shijuan
    const subjectIds = shijuan.subjectIds
    const subjects = []
    for (const subjectId of subjectIds) {
      const subject = await this.testPaperModel
        .findById(subjectId)
        .populate({ path: 'subject', model: 'Subject' })
        .exec()

      subjects.push(subject)
    }
    return subjects
  }
}
